package door.smartlift.top.service.impl;

import door.smartlift.top.common.utils.CollectionUtil;
import door.smartlift.top.config.PasswordHelper;
import door.smartlift.top.dao.SysUserMapper;
import door.smartlift.top.domain.SysUser;
import door.smartlift.top.domain.SysUserExample;
import door.smartlift.top.exception.MyDefineException;
import door.smartlift.top.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 * @author Admin
 * @date 2018/4/1
 */
@Slf4j
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordHelper passwordHelper;

    @Override
    public SysUser findUserByName(String username) {

        SysUserExample sysUserExample=new SysUserExample();

        sysUserExample.createCriteria().andUsernameEqualTo(username);

        List<SysUser> users=this.sysUserMapper.selectByExample(sysUserExample);

        if (CollectionUtil.isEmpty(users)){

            return null;
        }
        return users.get(0);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int createUser(SysUser sysUser) {

        SysUser user=this.findUserByName(sysUser.getUsername());

        if (user !=null){
            throw new MyDefineException("用户名重复");
        }

        sysUser.setPassword(passwordHelper.encryptcusPassword(sysUser));

        return this.sysUserMapper.insertSelective(sysUser);
    }
}
